<template>
  <div class="charts-search-block business-select-box">
    <div class="charts-search-block-content">
      <div class="charts-search-select">
        <span>{{ $t('report.mtbtSelect.failureTime') }}：</span>
        <el-select :clearable="false" v-model="formData.dataType" :placeholder="$t('common.base.pleaseSelect')" class="business-dateType-picker">
          <el-option
            v-for="item in dataTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-date-picker
          v-if="dataPickerType === 'monthrange'"
          class="business-date-picker business-select-mr"
          v-model="formData.monthTime"
          type="monthrange"
          :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          value-format="timestamp"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          :clearable="false">
        </el-date-picker>
        <el-date-picker
          v-if="dataPickerType === 'daterange'"
          class="business-date-picker"
          v-model="formData.dateTime"
          type="daterange"
          :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          value-format="timestamp"
          :default-time="['00:00:00', '23:59:59']"
          :clearable="false"
          align="right">
        </el-date-picker>
      </div>
      <div class="charts-search-select">
        <span>OEM：</span>
        <el-select 
          :placeholder="$t('common.base.pleaseSelect')"
          v-model="formData.oems" 
          @change="chooseOEM"
          :clearable="true"
          style="width:180px"
          multiple
          filterable
          collapse-tags>
          <el-option v-for="item in oemList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.base.systemKeyword.customer')}}：</span>
        <biz-search-customer-select style="width: 180px" :multiple="true" :value="customerIdList" @input="chooseCustomer" :remote-method="fetchCustomer" value-key="id" :collapsed="true" :placeholder="$t('report.common.allCustomer')"
        />
      </div>
      <div class="charts-search-select">
        <span>{{ $t('report.mtbtSelect.cause')}}：</span>
        <el-select 
          :placeholder="$t('common.base.pleaseSelect')"
          v-model="ssbReasons" 
          multiple
          filterable
          :clearable="true"
          style="width: 180px">
          <el-option v-for="item in ssbReasonsList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.base.productType')}}：</span>
        <biz-form-remote-select
          style="width: 280px"
          :remote-method="fetchCustomerProducts"
          :value="catalogIdsList"
          @input="inputProduct"
          :placeholder="$t('common.base.all')" 
          cleared
          :multiple="true"
          value-key="id"
        >
          <div class="customer-template-option" slot="option" slot-scope="{ option }">
            <h3>{{ option.label }}</h3>
          </div>
        </biz-form-remote-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('report.mtbtSelect.driverType')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="driveTypes" 
          multiple
          collapse-tags
          filterable
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in driveTypesList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('report.mtbtSelect.eographicalLocation')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="positions" 
          multiple
          collapse-tags
          filterable
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in positionsList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('report.mtbtSelect.powerSupplyType')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="backupPowerTypes" 
          multiple
          collapse-tags
          filterable
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in backupPowerTypesList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('report.mtbtSelect.failureStopCause')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="formData.causeOfFailures" 
          multiple
          collapse-tags
          filterable
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in failureReasons" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('report.mtbtSelect.fanStatus')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="fanStatus" 
          multiple
          collapse-tags
          filterable
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in fanStatusList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>

    </div>
    <div class="charts-search-block-operator">
      <el-button type='primary' @click="handlerSearchClick">
        {{ $t('common.base.search') }}
      </el-button>
    </div>
  </div>
</template>
<script>

import { lastDayOfMonth, firstDayOfMonth, nearDateBy, dayTimeEnd } from 'pub-bbx-utils';
import { t } from '@src/locales';
import http from 'src/util/HttpUtil';  
import * as ssbReportApi from 'src/api/ssbReports';   
import { getCustomerList } from '@src/api/CustomerApi'
import BizSearchProductSelect from '@src/component/business/BizSearchProductSelect/BizSearchProductSelect'
 
export default {
  name: 'mtbt-select',
  data() {
    return {
      formData:{
        dateTime: [], // 日时间
        monthTime: [], // 月时间
        oems:[],
        catalogIds: [], // 产品类型Ids
        causeOfFailures:[], // 故障原因
        dataType: 'month', // 日月维度
      },
      catalogIds:  [], // 产品id集合
      customerIdList: [],
      ssbReasons: [],
      driveTypes: [],
      positions: [],
      backupPowerTypes: [],
      fanStatus: [],
      dataTypeList: [
        {
          label:t('common.base.month'),
          value:'month'
        },
        {
          label:t('common.base.day2'),
          value:'day'
        },
      ],
      oemList: [], // OEM列表
      ssbReasonsList: [], // SSB原因列表
      driveTypesList: [], // 驱动器类型列表
      positionsList: [], // 地理位置列表
      backupPowerTypesList: [], // 后备电源类型列表
      fanStatusList: [], // 风机状态
      failureReasons:[],
      productTypeList:[],
      OEMFieldName:'',
      catalogIdsList: [], // 产品类型id
    }
  },
  computed:{
    dataPickerType(){
      return this.formData.dataType === 'month' ? 'monthrange' : 'daterange'
    }
  },
  components: {
    BizSearchProductSelect
  },
  created() {
    this.formData.dateTime = [+firstDayOfMonth(nearDateBy(5, 'month')), +dayTimeEnd()]
    this.formData.monthTime = [+firstDayOfMonth(nearDateBy(5, 'month')), +dayTimeEnd()]
    this.getRequestParam().then(res=>{
      this.getOemList()
    })
  },
  methods: {
    getOemList(){
      http.get('/api/ssbreport/outside/staff/calendar/getCustomerOEMDatabase').then(res=>{
        if(res.code == 0){
          this.oemList = res.data.database
          this.OEMFieldName = res.data.fieldName
          // this.formData.oems = res.data.database[0] ? [res.data.database[0]] : []
          this.getData()
        }
      })
    },
    inputProduct(val) {
      // console.log(val, 'valval')
      this.catalogIdsList = val
    },
    // 查询产品列表
    fetchCustomerProducts(params) {
      let { keyword, pageNum, pageSize } = params;
      let queryParams = {
        pageNum,
        keyword,
        pageSize,
      }
      return this.$http.post('/api/customer/outside/pc/catalog/pageList', queryParams).then(res => {
        if (!res || !res.result.list) return;

        res.result.list = res.result.list.map(item =>
          Object.freeze({
            label: item?.catalogName || '',
            value: item?.id || '',
            text: item.catalogName || '',
            name: item.catalogName || '',
            id: item.id || '',
            catalogNum: item.catalogNum || '',
          })
        );

        console.log(res.result, 'res.result.list')
        res.result.pageNum = pageNum
        res.result.pageSize = pageSize
        res.result.hasNextPage = res.result.total > res.result.pageNum * res.result.pageSize

        return res.result;
      });
      // return http.post('/api/customer/outside/pc/catalog/pageList', {...params})
    },
    getRequestParam() {
      return new Promise((resolve, reject)=>{
        this.getReasons()
        this.getProductTypes()
        http.get('/api/ssbreport/outside/productFault/getRequestParam').then(res => {
          if(res.code == 0){
            let { ssbReasons = [], driveTypes = [], positions = [], backupPowerTypes = [], fanStatus = [] } = res.data || {}
            this.ssbReasonsList = ssbReasons
            this.driveTypesList = driveTypes
            this.positionsList = positions
            this.backupPowerTypesList = backupPowerTypes
            this.fanStatusList = fanStatus

            this.ssbReasons = this.ssbReasonsList?.slice(0, 1) || []
            resolve(true)
          }else{
            throw res
          }
        }).catch(err=>{
          resolve(true)
        })
      })
      
    },
    chooseOEM(){
      this.productTypeList = []
      this.formData.catalogIds = []
      this.getProductTypes()
    },
    chooseCustomer(value){
      this.customerIdList = value
      this.getProductTypes()
    },
    fetchCustomer(params){
      const { oems } = this.formData;
      // 如果oems存在的话就传值
      if ( oems && oems.length > 0) {
        params['conditions'] = [{property:this.OEMFieldName, inValue:oems, key:null, operator:'in'}]
      } else {
        params['conditions'] = []
      }
      return getCustomerList({...params})
    },
    getProductTypes(){
      ssbReportApi.getProductTypesByOems(this.formData.oems).then(res=>{
        if(res.code === 0){
          this.productTypeList = res.data || []
        }
      })
    },
    getReasons(){
      ssbReportApi.getFailureReasons().then(res=>{
        if(res.code === 0){
          this.failureReasons = res.data
        }
      })
    },
    handlerSearchClick(){
      this.getData()
    },
    getSearchParams(){
      this.formData.catalogIds = []
      if (this.catalogIdsList.length) {
        this.catalogIdsList.map((item) => {
          this.formData.catalogIds.push(item.id)
        })
      }

      const { dataType, monthTime, dateTime, oems, catalogIds, causeOfFailures } = this.formData;
      const { ssbReasons, customerIdList, fanStatus, driveTypes, positions, backupPowerTypes } = this;
      let customerIds = [];
      try {
        customerIdList.forEach(item=>customerIds.push(item.id))
      } catch (error) {
        console.warn(error, 'error try catch customerIdList.forEach');
      }
      let params = {
        createDateStart:dataType == 'month' ? monthTime[0] : dateTime[0],
        createDateEnd:dataType == 'month' ? +lastDayOfMonth(this.formData.monthTime[1]) : this.formData.dateTime[1],
        oems,
        catalogIds,
        causeOfFailures,
        timeDimension:dataType,
        customerIds,
        isExport:false,
        fanStatus,
        ssbReasons,
        driveTypes,
        positions,
        backupPowerTypes
      }
      return params
    },
    getData(){
      const params = this.getSearchParams();
      this.$emit('change-loading', {type:1, state:true})
      http.post('/api/ssbreport/outside/mtbtReport/mtbtReportData', params).then(res=>{
        if(res.code == 0){
          this.$emit('updateData', {data:res.data, haveUsers:this.formData.oems.length > 0})
        }else{
          this.$message.error(res.message)
        }
      }).finally(()=>{
        this.$emit('change-loading', {type:1, state:false})
      })
    },
    export(){
      this.$emit('change-loading', {type:2, state:true})
      const params = this.getSearchParams();
      params.isExport = true;
      http.post('/api/ssbreport/outside/mtbtReport/mtbtReportExport', params, true, {responseType: 'blob'}).then(blob=>{
        let link = document.createElement('a');
        let url = URL.createObjectURL(blob);
        link.download = this.$t('report.mtbtSelect.MTBTReport');
        link.href = url;
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
          URL.revokeObjectURL(url);
          document.body.removeChild(link);
        }, 150);

      }).finally(() =>{
        this.$emit('change-loading', {type:2, state:false})
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../business.scss';
</style>
<style lang="scss">
</style>